package com.learn.xueer.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.tabs.TabLayout
import com.learn.xueer.R
import com.learn.xueer.app.appViewModel
import com.learn.xueer.app.base.BaseActivity
import com.learn.xueer.app.network.NetworkApi
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.app.util.CornerTransform
import com.learn.xueer.app.util.User
import com.learn.xueer.data.model.bean.Child
import com.learn.xueer.databinding.ActivityLoginBinding
import com.learn.xueer.ui.adapter.AccountAdapter
import com.learn.xueer.ui.viewmodel.RequestLoginViewModel
import kotlinx.android.synthetic.main.activity_login.cb
import kotlinx.android.synthetic.main.activity_login.et_account
import kotlinx.android.synthetic.main.activity_login.et_code
import kotlinx.android.synthetic.main.activity_login.et_pass
import kotlinx.android.synthetic.main.activity_login.et_real_name
import kotlinx.android.synthetic.main.activity_login.et_real_pass
import kotlinx.android.synthetic.main.activity_login.iv_captcha
import kotlinx.android.synthetic.main.activity_login.lin_quick
import kotlinx.android.synthetic.main.activity_login.lin_real
import kotlinx.android.synthetic.main.activity_login.tab_pic
import kotlinx.android.synthetic.main.activity_login.tv_check
import kotlinx.android.synthetic.main.activity_login.tv_login
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.view.afterTextChange
import me.hgj.jetpackmvvm.util.ActivityMessenger
import me.hgj.jetpackmvvm.util.get
import me.hgj.jetpackmvvm.util.startActivity


class LoginActivity : BaseActivity<RequestLoginViewModel, ActivityLoginBinding>() {
    var accountPop: PopupWindow? = null

    override fun initView(savedInstanceState: Bundle?) {
        NetworkApi.INSTANCE.cookieJar.clear()

        addLoadingObserve(mViewModel)
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        val useSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                ActivityMessenger.startActivityForResult(
                    this@LoginActivity, ProtocolActivity::class,
                    "data" to appViewModel.about.value?.use_agreement.toString(),
                    "name" to "学而时习个人信息保护指引"
                ) {
                    if (it != null) {
                        val data = it.get<String>("data") ?: ""

                    }
                }
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = resources?.getColor(R.color._0cb76c)!!
                ds.isUnderlineText = false
            }
        }
        val ysSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                ActivityMessenger.startActivityForResult(
                    this@LoginActivity, ProtocolActivity::class,
                    "data" to appViewModel.about.value?.privacy_agreement.toString(),
                    "name" to "学而时习隐私政策"
                ) {
                    if (it != null) {
                        val data = it.get<String>("data") ?: ""

                    }
                }

            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = resources?.getColor(R.color._0cb76c)!!
                ds.isUnderlineText = false
            }
        }
        val childSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                ActivityMessenger.startActivityForResult(
                    this@LoginActivity, ProtocolActivity::class,
                    "data" to appViewModel.about.value?.protect_agreement.toString(),
                    "name" to "儿童隐私保护政策"
                ) {
                    if (it != null) {
                        val data = it.get<String>("data") ?: ""

                    }
                }
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = resources?.getColor(R.color._0cb76c)!!
                ds.isUnderlineText = false
            }
        }

        SpanUtils.with(tv_check).append("我已阅读并同意").append("《使用协议》、")
            .setClickSpan(useSpan)
            .append("《隐私政策》、")
            .setClickSpan(ysSpan)
            .append("《儿童隐私保护政策》")
            .setClickSpan(childSpan)
            .create()
        mViewModel.captcha()
        mViewModel.loginType = 0
        tab_pic.getTabAt(0)?.select()
        tab_pic.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(p0: TabLayout.Tab?) {
                if (p0?.position == 0) {
                    mViewModel.loginType = 0
                    lin_quick.visibility = View.VISIBLE
                    lin_real.visibility = View.GONE
                    mViewModel.selectSchool.value = null
                } else {
                    mViewModel.loginType = 1
                    lin_quick.visibility = View.GONE
                    lin_real.visibility = View.VISIBLE
                }
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {

            }

            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

        })

        et_account.afterTextChange {
            if (it.isEmpty()
                || et_code.text.toString().isEmpty()
                || et_pass.text.toString().isEmpty()
            ) {
                loginUnable()
            } else {
                loginAble()
            }
        }
        et_pass.afterTextChange {
            if (it.isEmpty() || et_account.text.toString().isEmpty()
                || et_code.text.toString().isEmpty()
            ) {
                loginUnable()
            } else {
                loginAble()
            }
        }

        et_real_pass.afterTextChange {
            if (it.isEmpty() || et_real_name.text.toString()
                    .isEmpty() || mViewModel.selectSchool.value?.name?.isEmpty() == true
                || et_code.text.toString().isEmpty()
            ) {
                loginUnable()
            } else {
                loginAble()
            }
        }
        et_real_name.afterTextChange {
            if (it.isEmpty() || et_real_pass.text.toString()
                    .isEmpty() || mViewModel.selectSchool.value?.name?.isEmpty() == true
                || et_code.text.toString().isEmpty()
            ) {
                loginUnable()
            } else {
                loginAble()
            }
        }

        et_code.afterTextChange {
            if (mViewModel.loginType == 0) {
                if (it.isEmpty() || et_account.text.toString().isEmpty() || et_pass.text.toString()
                        .isEmpty()
                ) {
                    loginUnable()
                } else {
                    loginAble()
                }
            } else {
                if (it.isEmpty() || et_real_name.text.toString().isEmpty()
                    || et_real_pass.text.toString().isEmpty()
                    || mViewModel.selectSchool.value?.name?.isEmpty() == true
                ) {
                    loginUnable()
                } else {
                    loginAble()
                }
            }

        }
        mViewModel.aboutReq()

        var loginAccount = CacheUtil.getLoginAccount()
        if (loginAccount.isNotEmpty() && loginAccount.size != 0) {
            mViewModel.username.set(loginAccount[0].account)
            mViewModel.password.set(loginAccount[0].pass)
        }
    }

    private fun loginAble() {
        tv_login.setTextColor(resources?.getColor(R.color.white) ?: 0)
        tv_login.background = resources?.getDrawable(R.drawable.gra_29f19c)
    }

    private fun loginUnable() {
        tv_login.setTextColor(resources?.getColor(R.color.b5b5b5) ?: 0)
        tv_login.background = resources?.getDrawable(R.drawable.rec_e5e5e5)
    }

    override fun createObserver() {
        mViewModel.captchaData.observe(this@LoginActivity, Observer {
            dismissLoading()

            val transformation = CornerTransform(
                this,
                SizeUtils.dp2px(22.5f).toFloat()
            )
            transformation.setExceptCorner(true, false, true, false)

            Glide.with(this).load(it)
                .apply(RequestOptions.bitmapTransform(transformation))
                .into(iv_captcha)
        })
        mViewModel.userInfo.observe(this, Observer { resultState ->
            parseState(resultState, {
                ToastUtils.showShort("登录成功")
                CacheUtil.setUser(it)

                startActivity(MainActivity::class)
                this@LoginActivity.finish()
            }, {
                ToastUtils.showShort(it.errorMsg)
            })
        })

        mViewModel.schoolResult.observe(this, Observer { resultState ->
            parseState(resultState, {


            }, {
                ToastUtils.showShort(it.errorMsg)

            })
        })
    }

    inner class ProxyClick {

        fun login() {
            if (!cb.isChecked) {
                ToastUtils.showShort("请先阅读并同意使用协议及隐私政策")
                return
            }
            if (tab_pic.selectedTabPosition == 0) {
                if (mViewModel.username.get().isEmpty() || mViewModel.password.get()
                        .isEmpty()
                    || mViewModel.capture.value?.isEmpty() == true
                ) {
                    return
                }
            } else if (tab_pic.selectedTabPosition == 1) {
                if (mViewModel.selectSchool.value?.name.isNullOrEmpty() || mViewModel.realUsername.get()
                        .isEmpty() || mViewModel.realPassword.get()
                        .isEmpty()
                    || mViewModel.capture.value?.isEmpty() == true
                ) {
                    return
                }
            }

            if (tab_pic.selectedTabPosition == 0) {
                mViewModel.loginReq(mViewModel.username.get(), mViewModel.password.get(), "")
            } else {
                mViewModel.loginReq(
                    mViewModel.realUsername.get(),
                    mViewModel.realPassword.get(),
                    (mViewModel.selectSchool.value?.id ?: 0).toString()
                )

            }
        }

        fun reset() {
            showLoading()
            mViewModel.captcha()
        }

        fun forget() {
            startActivity(ForgetActivity::class)
        }

        fun school() {
            ActivityMessenger.startActivityForResult(
                this@LoginActivity,
                SelectSchoolActivity::class
            ) {
                if (it != null) {
                    val name = it.get<String>("name") ?: ""
                    val id = it.get<Int>("id") ?: 0
                    val city = it.get<String>("city") ?: ""
                    var child = Child()
                    child.city = city
                    child.name = name
                    child.id = id
                    mViewModel.selectSchool.value = child
                }
            }
        }

        fun list() {
            initPop()
            if (accountPop?.isShowing == true) {
                accountPop?.dismiss()
            }
            accountPop?.showAsDropDown(mDatabind.linAccount)
        }

    }

    @SuppressLint("ResourceAsColor")
    private fun initPop() {
        var loginAccount = CacheUtil.getLoginAccount()
        if (loginAccount.isEmpty()) {
            return
        }
        val accountPopView = LayoutInflater.from(this@LoginActivity)
            .inflate(R.layout.account_list_dialog, null)
        accountPop = PopupWindow(
            accountPopView,
            mDatabind.linAccount.width,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        accountPop?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        accountPop?.isOutsideTouchable=true
        var rv = accountPopView.findViewById<RecyclerView>(R.id.rv_account)
        var accountAdapter = AccountAdapter(loginAccount)
        rv.layoutManager = LinearLayoutManager(this@LoginActivity)
        rv.addItemDecoration(
            DividerItemDecoration(
                this@LoginActivity,
                DividerItemDecoration.VERTICAL
            )
        )
        rv.adapter = accountAdapter
        accountAdapter.setOnItemChildClickListener { baseQuickAdapter, view, i ->
            when (view.id) {
                R.id.iv_delete -> {
                    CacheUtil.deleteLoginAccount(loginAccount[i])
                    accountAdapter.data.removeAt(i)
                    accountAdapter.notifyDataSetChanged()
                }
            }
        }
        accountAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            mViewModel.username.set(accountAdapter.data[i].account)
            mViewModel.password.set(accountAdapter.data[i].pass)
            accountPop?.dismiss()
        }
    }

}